package com.wasu.sdk_ott.http.network.interceptor;

import static com.alibaba.fastjson.util.IOUtils.UTF8;

import android.text.TextUtils;
import android.util.Log;

import com.wasu.sdk_ott.http.network.error.ErrorUtils;
import com.wasu.sdk_ott.http.network.error.Report;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * ------------------------------------------------------
 * Copyright (C) 2021 wasu company, All rights reserved.
 * ------------------------------------------------------
 *  @author Created by yingjh
 *  @date
 */
public class ErrorInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;
        String posturl = request.url().toString();
        String urlbody = "";
        //String method = request.method();
        RequestBody requestBody = request.body();
        //Log.d("yingjh", "OkHttp-----request.url()=" + posturl);
        //Log.d("yingjh", "OkHttp-----request.method=" + method);
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            urlbody = buffer.readString(charset);
        }

        try {
            response = chain.proceed(request);
        } catch (Exception e) {
           if(e.toString().contains("java.io.InterruptedIOException: thread interrupted")){
               Log.d("Report","InterruptedIOException: thread interrupted");
               /*线程中断不需要上报数据*/
           }else {
               Report.report("NetLinkError", "网络发生IOException", ErrorUtils.getServieName(posturl), posturl, urlbody, e.toString());
           }
            throw e;
        }


        int code = response.code();
        if ((code < 200) || (code >= 300)) {
            Report.report("NetStatusError", "网络状态异常", ErrorUtils.getServieName(posturl), posturl, urlbody, "" + code + "|" + response.message());
        } else {
            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
            //个新的response给应用层处理
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            String result = responseBody.string();
            if (TextUtils.isEmpty(result)) {/*返回数据为空时上报*/
                Report.reportEmptybyUrl(posturl, urlbody);
            } else {
                //测试用
                //Report.print(posturl, urlbody);
            }
        }
        return response;
    }
}
